package task.dao;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

import task.ITask;


public class TaskDaoCPImpl implements TaskDao {

	private String[] tasks;

	public TaskDaoCPImpl() throws IOException {
//		Properties props = System.getProperties();
//		for (Map.Entry<Object, Object> e : props.entrySet()) {
//			System.out.printf("%s : %s%n", e.getKey(), e.getValue());
//		}
		String cpString = System.getProperty("java.class.path");
		String sep = System.getProperty("path.separator");
		String[] cps = cpString.split(sep);
		ArrayList<String> list = new ArrayList<String>();
		for (String cp : cps) {
			if (!cp.toLowerCase().endsWith(".jar")) {
				File dir = new File(cp);
				addClasses(list, dir, dir.getCanonicalPath().length()+1);
			}
		}
		tasks = list.toArray(new String[0]);
	}
	private void addClasses(ArrayList<String> list, File file, int prefixLen) throws IOException {
		if (file.isDirectory()) {
			for (File child : file.listFiles()) {
				addClasses(list, child, prefixLen);
			}
		} else {
			if (file.getName().endsWith(".class")) {
				String clsName = file.getCanonicalPath().substring(prefixLen);
				clsName = clsName.substring(0, clsName.length() - 6);
				clsName = new String(replaceSlashes(clsName.toCharArray()));
				try {
					Class<?> cls = Class.forName(clsName);
					if (ITask.class.isAssignableFrom(cls) && (((Modifier.INTERFACE | Modifier.ABSTRACT) & cls.getModifiers()) == 0)) {
						list.add(clsName);
					}
				} catch (ClassNotFoundException e) {
				}
			}
		}
	}
	private static char[] replaceSlashes(char[] tab) {
		for (int i=0 ; i<tab.length ; i++) {
			switch (tab[i]) {
			case '\\':
			case '/':
				tab[i] = '.';
				break;
			}
		}
		return tab;
	}
	@Override
	public void delete(String taskClass) {
		throw new UnsupportedOperationException();
	}

	@Override
	public String[] getTasks() {
		return tasks;
	}

	@Override
	public void save(String taskClass) {
		throw new UnsupportedOperationException();
	}
	public static void main(String[] args) throws IOException {
		TaskDaoCPImpl td = new TaskDaoCPImpl();
	}
}
